//
//  MainViewController.m
//  Travel
//
//  Created by lanou3g on 15/11/18.
//  Copyright © 2015年 lanou3g. All rights reserved.
//

#import "MainViewController.h"

#import "SDCollectionViewCell.h"
#import "SDCycleScrollView.h"

#import "HeadView.h"
#import "HeadModel.h"
#import "TitleModel.h"
#import "DataModel.h"
#import "ContentCell.h"
@interface MainViewController ()<UITableViewDataSource,UITableViewDelegate>

//轮播图的视图
@property (nonatomic,strong) UIView *headView;

//内容表视图
@property (nonatomic,strong) UITableView *tableV;

//轮播图
@property (nonatomic,strong) SDCycleScrollView *SDVC;


@property (nonatomic,strong) NSMutableArray *imageArr;

//存放数据源的数组
@property (nonatomic,strong) NSMutableArray *sourcesArray;
@property (nonatomic,strong) NSMutableArray *titleArray;
@property (nonatomic,strong) NSMutableArray *dataArray;

//判断从沙盒还是从数据库存储

@property(nonatomic,assign) BOOL isHas;


@end

@implementation MainViewController

//数组的懒加载

//-(void)setSourcesArray:(NSMutableArray *)sourcesArray
//{
//    if (_sourcesArray != sourcesArray) {
//        self.sourcesArray = [NSMutableArray new];
//    }
//}

- (void)viewDidLoad {
    
    //初始化数组
    self.sourcesArray = [NSMutableArray new];
    self.imageArr = [NSMutableArray new];
    self.titleArray = [NSMutableArray new];
    self.dataArray = [NSMutableArray new];
    
    
    //UIView的数据请求
    


    
    
    
    
    
    //视图布局
    [self layoutViews];
    
//    [self.headView addSubview:self.SDVC];
    
    
    
    [self layoutLunBo:self.imageArr];
    
    //设置代理
    self.tableV.delegate = self;
    self.tableV.dataSource = self;
    
    
    [self requestUIViewData];
    [self requestTableViewData];
    
    
    [self.tableV registerClass:[ContentCell class] forCellReuseIdentifier:@"cell"];
    [self.view  addSubview:self.headView];



    
   
}

//视图的生命周期

- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    
    [self requestUIViewData];
    
//    [self.headView addSubview:self.SDVC];

    [self.view  addSubview:self.headView];
    
//    [self layoutLunBo:self.imageArr];
    
    
}

//视图的布局

-(void)layoutViews
{
    
    self.headView = [[UIView alloc]initWithFrame:CGRectMake(5, 68, self.view.frame.size.width, 200)];
    
    self.tableV = [UITableView new];
    
    self.tableV.frame = CGRectMake(0,  200, self.view.frame.size.width, self.view.frame.size.height - self.headView.frame.size.height);
    
    
    //使用第三方
//    self.SDVC = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 200) imageURLStringsGroup:nil];
//    
//    [self.headView addSubview:self.SDVC];
    [self.view  addSubview:self.headView];
    [self.view addSubview:self.tableV];
    
    self.headView = [[UIView alloc]initWithFrame:CGRectMake(5, 68, self.view.frame.size.width, 70)];
    
    
    
    self.tableV = [UITableView new];
    
    self.tableV.frame = CGRectMake(0,  170, self.view.frame.size.width, self.view.frame.size.height - self.headView.frame.size.height);
    
    
    
    
    
    [self.view addSubview:self.tableV];
    
    

}



//UIView的本地存储

-(void)requestFromLocal
{
    
    //获取沙盒路径
    NSString *path = NSHomeDirectory();
    
    //创建一个存储plist文件的路径
    
    NSString *plistPath = [path stringByAppendingPathComponent:@"/Documents/pic.plist"];
    NSMutableArray *arr = [NSMutableArray new];
    
    //把图片添加到数组
    
    for (HeadModel *hModel in self.sourcesArray) {
        [arr addObject:hModel.title_page];
    }
    NSLog(@"Arr= %@",arr);
    
    //写入plist文件

    for (HeadModel *hModel in self.sourcesArray) {
        [arr addObject:hModel.title_page];
    }
    
   //写入plist文件
    if ([arr writeToFile:plistPath atomically:YES]) {
        NSLog(@"写入成功");
    }

    NSLog(@"Arr= %@",arr);
    
    
    
}
//UIView的网络数据请求
-(void)requestUIViewData
{
    //子线程
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
    NSString *url = @"http://api.breadtrip.com/hunter/products/more/?start=0";
    
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        if (error) {
            NSLog(@"解析错误");
            return ;
        }
        NSMutableDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        
            NSArray *product_listArr = jsonDic[@"product_list"];
        
            for (NSDictionary *tab_listDic in product_listArr) {
        
                HeadModel *hModel = [HeadModel new];
               
                [hModel setValuesForKeysWithDictionary:tab_listDic];
                
                [self.sourcesArray addObject:hModel];
                
                //NSLog(@"picurl=%@",hModel.title_page);
            }
            
            NSLog(@"----》》》%@",self.sourcesArray);
            
            //返回主线程
            dispatch_async(dispatch_get_main_queue(), ^{
                
                //每次加载之前先清空数组
                [self.imageArr removeAllObjects];
                
                for (int i = 0; i < self.sourcesArray.count; i++) {
                    
                    if (i < 4) {
                        
                        HeadModel *model = self.sourcesArray[i];
                        [self.imageArr addObject:model.title_page];
                    }
                }
                [self layoutLunBo:self.imageArr];
            });
        }];
        [dataTask resume];
    });
}

//UITableView的解析数据

-(void)requestTableViewData
{
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        NSString *url = @"http://api.breadtrip.com/destination/v3/?last_modified_since=0";
        
        NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
        
        NSURLSession *session = [NSURLSession sharedSession];
        
        NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            
            if (error) {
                NSLog(@"解析错误");
                return ;
            }
            
            NSMutableDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            
            
            NSArray *elementsArray = jsonDic[@"elements"];
            
            
            for (NSDictionary *titleDic in elementsArray) {
                
                //TitleModel *tModel = [TitleModel new];
                
                //[tModel setValuesForKeysWithDictionary:titleDic];
                
                
                NSString *title = titleDic[@"title"];
                
                [self.titleArray addObject:title];
            NSArray *elementsArray = jsonDic[@"elements"];
            
            for (NSDictionary *titleDic in elementsArray) {
                
                TitleModel *tModel = [TitleModel new];
                [tModel setValuesForKeysWithDictionary:titleDic];
                
                [self.titleArray addObject:tModel];
                
                
                NSArray *dataArray = titleDic[@"data"];
                
                for (NSDictionary *dataDic in dataArray) {
                    
                    DataModel *dModel = [DataModel new];
                    [dModel setValuesForKeysWithDictionary:dataDic];
                    [self.dataArray addObject:dModel];
                    
                }
            }
            
            [self.tableV performSelectorOnMainThread:@selector(reloadData) withObject:self waitUntilDone:nil];
                
            }
        }];
        
        [dataTask resume];
    });
    
}

//轮播图的设置

-(void)layoutLunBo:(NSMutableArray *)picArr
{
    
    
    //设置轮播图的属性
    
//    self.SDVC.infiniteLoop = YES;//是否循环轮播
//    
//    self.SDVC.pageControlStyle = SDCycleScrollViewPageContolStyleAnimated;
//    
//    //自定义轮播图的时间间隔
//    self.SDVC.autoScrollTimeInterval = 0.1;
//    
//    self.SDVC.dotColor = [UIColor cyanColor];
//    
//    
//    [self.SDVC setImageURLStringsGroup:picArr];
    
}



#pragma mark -- UITableView的代理方法


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    return self.dataArray.count;
}


-(NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
{
    return 1;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    
    
    ContentCell *cell = [self.tableV dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    
 
    
    
    
    //TitleModel *tModel = self.titleArray[indexPath.row];
    DataModel  *dModel = self.dataArray[indexPath.row];
    
    //cell.tModel = tModel;
    cell.dModel = dModel;
  
    

    
   
   
    for (int i = 0; i < self.titleArray.count; i++) {
        
        cell.titleLabel.text = self.titleArray[i];
        
    }
    
     NSLog(@"titleArr=%@",self.titleArray[5]);
   
    

    
    cell.textLabel.text = @"哈哈哈";
    
  
    
    return cell;
    
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 200;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
